

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Fly542">
  <meta name="keywords" content="">
  
    <meta name="description" content="获取当前的时间戳示例代码如下： 123456789101112131415use std::time::&amp;#123;SystemTime&amp;#125;;fn get_timestamp() -&gt; u64 &amp;#123;    match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) &amp;#123;        Ok(now) &#x3D;">
<meta property="og:type" content="article">
<meta property="og:title" content="rust 实用代码总结">
<meta property="og:url" content="http://fly542.cn/2020/07/31/03%E8%BD%AF%E4%BB%B6%E5%BC%80%E5%8F%91/02Rust/00rust%E5%AE%9E%E7%94%A8%E4%BB%A3%E7%A0%81%E6%B1%87%E6%80%BB/index.html">
<meta property="og:site_name" content="Fly542 技术沉淀">
<meta property="og:description" content="获取当前的时间戳示例代码如下： 123456789101112131415use std::time::&amp;#123;SystemTime&amp;#125;;fn get_timestamp() -&gt; u64 &amp;#123;    match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) &amp;#123;        Ok(now) &#x3D;">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-07-31T02:27:20.000Z">
<meta property="article:modified_time" content="2024-10-17T09:40:02.019Z">
<meta property="article:author" content="Fly542">
<meta property="article:tag" content="rust">
<meta name="twitter:card" content="summary_large_image">
  
  
  <title>rust 实用代码总结 - Fly542 技术沉淀</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"fly542.cn","root":"/","version":"1.8.14","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 6.0.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Fly542 技术沉淀</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="rust 实用代码总结">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2020-07-31 10:27" pubdate>
        2020年7月31日 上午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      4.3k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      36 分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">rust 实用代码总结</h1>
            
            <div class="markdown-body">
              <h1 id="获取当前的时间戳"><a href="#获取当前的时间戳" class="headerlink" title="获取当前的时间戳"></a>获取当前的时间戳</h1><p>示例代码如下：</p>
<figure class="highlight rust"><table><tr><td class="gutter"><div class="code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></div></td><td class="code"><pre><code class="hljs rust"><span class="hljs-keyword">use</span> std::time::&#123;SystemTime&#125;;<br><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">get_timestamp</span></span>() -&gt; <span class="hljs-built_in">u64</span> &#123;<br>    <span class="hljs-keyword">match</span> SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) &#123;<br>        <span class="hljs-literal">Ok</span>(now) =&gt; &#123;<br>            now.as_secs()<br>        &#125;,<br>        _ =&gt; &#123;<br>            std::<span class="hljs-built_in">u64</span>::MAX<br>        &#125;,<br>    &#125;<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() &#123;<br>    <span class="hljs-built_in">println!</span>(<span class="hljs-string">&quot;Hello, world! now=&#123;&#125;&quot;</span>, get_timestamp());<br>&#125;<br></code></pre></td></tr></table></figure>

<h1 id="实现函数重载"><a href="#实现函数重载" class="headerlink" title="实现函数重载"></a>实现函数重载</h1><p>函数重载<br>rust本身不支持函数重载，但是可以用泛型trait实现类似于重载的效果</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><code class="hljs rust"><span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">With</span></span>&lt;T&gt; &#123;<br>    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">with</span></span>(value: T) -&gt; <span class="hljs-keyword">Self</span>;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Foo</span></span> &#123;<br>    bar: <span class="hljs-built_in">String</span>,<br>    baz: <span class="hljs-built_in">i32</span>,<br>    quux: <span class="hljs-built_in">bool</span>,<br>&#125;<br><br><span class="hljs-keyword">impl</span> <span class="hljs-built_in">Default</span> <span class="hljs-keyword">for</span> Foo &#123;<br>    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">default</span></span>() -&gt; <span class="hljs-keyword">Self</span> &#123;<br>        Foo &#123;<br>            bar: <span class="hljs-string">&quot;&quot;</span>.to_string(),<br>            baz: <span class="hljs-number">0</span>,<br>            quux: <span class="hljs-literal">false</span>,<br>        &#125;<br>    &#125;<br>&#125;<br><br><span class="hljs-keyword">impl</span> Foo &#123;<br>    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">new</span></span>() -&gt; <span class="hljs-keyword">Self</span> &#123;<br>        Foo &#123;<br>            ..<span class="hljs-built_in">Default</span>::default()<br>        &#125;<br>    &#125;<br>&#125;<br><br><span class="hljs-keyword">impl</span> With&lt;<span class="hljs-built_in">String</span>&gt; <span class="hljs-keyword">for</span> Foo &#123;<br>    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">with</span></span>(x: <span class="hljs-built_in">String</span>) -&gt; <span class="hljs-keyword">Self</span> &#123;<br>        Foo &#123;<br>            bar: x,<br>            ..<span class="hljs-built_in">Default</span>::default()<br>        &#125;<br>    &#125;<br>&#125;<br><br><span class="hljs-keyword">impl</span> With&lt;<span class="hljs-built_in">i32</span>&gt; <span class="hljs-keyword">for</span> Foo &#123;<br>    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">with</span></span>(x: <span class="hljs-built_in">i32</span>) -&gt; <span class="hljs-keyword">Self</span> &#123;<br>        Foo &#123;<br>            baz: x,<br>            ..<span class="hljs-built_in">Default</span>::default()<br>        &#125;<br>    &#125;<br>&#125;<br><br><span class="hljs-keyword">impl</span> With&lt;<span class="hljs-built_in">bool</span>&gt; <span class="hljs-keyword">for</span> Foo &#123;<br>    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">with</span></span>(x: <span class="hljs-built_in">bool</span>) -&gt; <span class="hljs-keyword">Self</span> &#123;<br>        Foo &#123;<br>            quux: x,<br>            ..<span class="hljs-built_in">Default</span>::default()<br>        &#125;<br>    &#125;<br>&#125;<br><br><span class="hljs-meta">#[test]</span><br><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">name</span></span>() &#123;<br>    <span class="hljs-keyword">let</span> a = Foo::with(<span class="hljs-number">1</span>);<br>&#125;<br></code></pre></td></tr></table></figure>

<h1 id="vec合并数据时防止出现拷贝的方法"><a href="#vec合并数据时防止出现拷贝的方法" class="headerlink" title="vec合并数据时防止出现拷贝的方法"></a>vec合并数据时防止出现拷贝的方法</h1><p>当结构体中使用Vec<u8>在头部插入一个新的Vec<u8>数据时可以通过mem::replace方法来减少数据的拷贝。</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><code class="hljs rust"><span class="hljs-keyword">use</span> std::mem;<br><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Myvec</span></span> &#123;<br>    data: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u8</span>&gt;,<br>    count: <span class="hljs-built_in">usize</span>,<br>&#125;<br><br><span class="hljs-keyword">impl</span> Myvec &#123;<br>    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">new</span></span>() -&gt; Myvec &#123;<br>        Myvec &#123;<br>            data : <span class="hljs-built_in">Vec</span>::new(),<br>            count : <span class="hljs-number">0</span>,<br>        &#125;<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">append</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>, d:&amp;<span class="hljs-keyword">mut</span> <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u8</span>&gt;) &#123;<br>        <span class="hljs-keyword">self</span>.data.append(d);<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">pre_insert</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>, d:<span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u8</span>&gt;) &#123;<br>    <span class="hljs-comment">// 使用replace 逆向实现数据的插入，防止clone数据</span><br>        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> old = mem::replace(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>.data, d);<br>        <span class="hljs-keyword">self</span>.data.append(&amp;<span class="hljs-keyword">mut</span> old);<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">push</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>, u:<span class="hljs-built_in">u8</span>) &#123;<br>        <span class="hljs-keyword">self</span>.data.push(u);<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">print</span></span>(&amp;<span class="hljs-keyword">self</span>) &#123;<br>        <span class="hljs-built_in">println!</span>(<span class="hljs-string">&quot;data&#123;:#?&#125;&quot;</span>, <span class="hljs-keyword">self</span>.data);<br>    &#125;<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() &#123;<br>    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> v1 = Myvec::new();<br>    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> v2:<span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u8</span>&gt; = <span class="hljs-built_in">Vec</span>::new();<br>    v2.push(<span class="hljs-number">3</span>);<br>    v2.push(<span class="hljs-number">4</span>);<br>    v1.push(<span class="hljs-number">1</span>);<br>    v1.push(<span class="hljs-number">2</span>);<br>    v1.pre_insert(v2);<br>    v1.print();<br>&#125;<br><br></code></pre></td></tr></table></figure>

<h1 id="打印变量地址"><a href="#打印变量地址" class="headerlink" title="打印变量地址"></a>打印变量地址</h1><figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>()&#123;<br>    <span class="hljs-keyword">let</span> a:<span class="hljs-built_in">i32</span> = <span class="hljs-number">5</span>;<br>    <span class="hljs-comment">//&amp;a先转成raw指针，然后再把指针转成usize，这个可以print的</span><br>    <span class="hljs-keyword">let</span> addr = &amp;a <span class="hljs-keyword">as</span> *<span class="hljs-keyword">const</span> <span class="hljs-built_in">i32</span> <span class="hljs-keyword">as</span> <span class="hljs-built_in">usize</span>;<br>    <span class="hljs-built_in">println!</span>(<span class="hljs-string">&quot;addr：0x&#123;:X&#125;&quot;</span>,addr);<br><br>    <span class="hljs-comment">//为了验证刚才的地址是不是正确的，我们修改这个指针指向的数据</span><br>    <span class="hljs-comment">//pa就是addr对应的raw指针</span><br>    <span class="hljs-keyword">let</span> pa = addr <span class="hljs-keyword">as</span> *<span class="hljs-keyword">mut</span> <span class="hljs-built_in">i32</span>;<br>    <span class="hljs-comment">//解引用，*pa其实就是&amp;mut a了，给他赋值100</span><br>    <span class="hljs-keyword">unsafe</span>&#123;*pa = <span class="hljs-number">100</span>&#125;;<br><br>    <span class="hljs-comment">//打印a，可以看到a已经变成100了</span><br>    <span class="hljs-built_in">println!</span>(<span class="hljs-string">&quot;value:&#123;&#125;&quot;</span>,a);<br>&#125;<br></code></pre></td></tr></table></figure>

<h1 id="打印变量T的类型"><a href="#打印变量T的类型" class="headerlink" title="打印变量T的类型"></a>打印变量T的类型</h1><figure class="highlight reasonml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs reasonml">fn print_type_of&lt;T&gt;(_: &amp;T) &#123;<br>    println!(<span class="hljs-string">&quot;&#123;&#125;&quot;</span>, std::any::type_name::&lt;T&gt;<span class="hljs-literal">()</span>)<br>&#125;<br>fn main<span class="hljs-literal">()</span> &#123;<br>    <span class="hljs-keyword">let</span> s = String::from(<span class="hljs-string">&quot;hello&quot;</span>);<br>    <span class="hljs-keyword">let</span> <span class="hljs-built_in">bytes</span> = s.into<span class="hljs-constructor">_bytes()</span>;<br>    assert_eq!(&amp;<span class="hljs-literal">[<span class="hljs-number">104</span>, <span class="hljs-number">101</span>, <span class="hljs-number">108</span>, <span class="hljs-number">108</span>, <span class="hljs-number">111</span>]</span><span class="hljs-literal">[..]</span>, &amp;<span class="hljs-built_in">bytes</span><span class="hljs-literal">[..]</span>);<br>    print<span class="hljs-constructor">_type_of(&amp;<span class="hljs-params">bytes</span>)</span>;<br>    <span class="hljs-keyword">let</span> mut mb = <span class="hljs-built_in">bytes</span>;<br>    print<span class="hljs-constructor">_type_of(&amp;<span class="hljs-params">mb</span>)</span>;<br>    print<span class="hljs-constructor">_type_of(&amp;<span class="hljs-params">mut</span> <span class="hljs-params">mb</span>)</span>;<br>    <span class="hljs-keyword">let</span> mut x = &amp;mut mb;<br>    print<span class="hljs-constructor">_type_of(&amp;<span class="hljs-params">x</span>)</span>;<br>    <span class="hljs-keyword">let</span> y = &amp;mut x;<br>    print<span class="hljs-constructor">_type_of(&amp;<span class="hljs-params">y</span>)</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<h1 id="同一个crate内-不同lib或程序间的引用"><a href="#同一个crate内-不同lib或程序间的引用" class="headerlink" title="同一个crate内 不同lib或程序间的引用"></a>同一个crate内 不同lib或程序间的引用</h1><p>在同一个大型项目中，可能会建立多个lib，有时候想要以外部调用库的方式测试其中的某个lib的某项功能，这时怎么修改Cargo.toml文件引用工程内的某个lib？<br>答案是修改Cargo.toml 文件中的[dependencies]</p>
<p>参考arnl/test_simple/test_redis/Cargo.toml</p>
<figure class="highlight ini"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs ini"><span class="hljs-section">[package]</span><br><span class="hljs-attr">name</span> = <span class="hljs-string">&quot;test_redis&quot;</span><br><span class="hljs-attr">version</span> = <span class="hljs-string">&quot;0.1.0&quot;</span><br><span class="hljs-attr">authors</span> = [<span class="hljs-string">&quot;wanghaibin &lt;wanghaibin@xx.com&gt;&quot;</span>]<br><span class="hljs-attr">edition</span> = <span class="hljs-string">&quot;2018&quot;</span><br><br><span class="hljs-comment"># See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html</span><br><br><span class="hljs-section">[dependencies]</span><br><span class="hljs-attr">redis</span> = &#123; path = <span class="hljs-string">&quot;../../src/libredis/&quot;</span> &#125;<br><br></code></pre></td></tr></table></figure>

<p>在非tests目录下的测试程序arnl/test_simple/test_redis/src内容如下</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs rust"><span class="hljs-keyword">use</span> redis::&#123;redis_string, redis_client&#125;;<br><br><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() &#123;<br>    <span class="hljs-built_in">println!</span>(<span class="hljs-string">&quot;Hello, world!&quot;</span>);<br>    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> stream = redis_client::RedisClient::new(<span class="hljs-string">&quot;127.0.0.1:6379&quot;</span>, &amp;<span class="hljs-number">0</span>, &amp;<span class="hljs-number">3</span>).unwrap();<br>    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> rstr = redis_string::RedisString::new(&amp;<span class="hljs-keyword">mut</span> stream);<br>    <span class="hljs-keyword">let</span> key = <span class="hljs-string">&quot;incrbyfloat_test&quot;</span>;<br>    <span class="hljs-built_in">println!</span>(<span class="hljs-string">&quot;xxxx=&#123;:#?&#125;&quot;</span>,rstr.incrbyfloat(key, <span class="hljs-number">2.1</span>));<br>&#125;<br></code></pre></td></tr></table></figure>

<h1 id="有趣的所有权问题问题"><a href="#有趣的所有权问题问题" class="headerlink" title="有趣的所有权问题问题"></a>有趣的所有权问题问题</h1><p>代码1</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() &#123;<br>    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> v = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>];<br>    <span class="hljs-keyword">let</span> first = &amp;v[<span class="hljs-number">0</span>];<br>    v.push(<span class="hljs-number">5</span>);<br>    <span class="hljs-built_in">println!</span>(<span class="hljs-string">&quot;Hello, world!, first=&#123;&#125;&quot;</span>, first);<br>&#125;<br></code></pre></td></tr></table></figure>
<p>代码2</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() &#123;<br>    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> v = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>];<br>    <span class="hljs-keyword">let</span> first = &amp;v[<span class="hljs-number">0</span>];<br>    <span class="hljs-built_in">println!</span>(<span class="hljs-string">&quot;Hello, world!, first=&#123;&#125;&quot;</span>, first);<br>    v.push(<span class="hljs-number">5</span>);<br>&#125;<br><br></code></pre></td></tr></table></figure>

<p>上述<code>代码1</code>会编译报错，提示<code>error[E0502]: cannot borrow </code>v<code> as mutable because it is also borrowed as immutable</code></p>
<p>而<code>代码2</code>却可以正常编译通过，为什么那？</p>
<p>个人认为这正是rust在在编译期发现问题的优点之一，代码1报借用和可变借用同时存在错误，是因为在print的时候使用first，这时进行所有权规则检查，发现了E0502错误。而<code>代码2</code>为什么没有报错，是因为在编译时，运行到print进行所有权检测，此时还没有发生所有权问题，而在检测后续的push时first已经没有任何引用或使用，所以相关所有权规则没有问题</p>
<h1 id=""><a href="#" class="headerlink" title=""></a></h1>
            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E8%BD%AF%E4%BB%B6%E5%BC%80%E5%8F%91/">软件开发</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/rust/">rust</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2020/07/31/04DevOps/04goreplay%E5%BC%95%E6%B5%81%E6%B5%8B%E8%AF%95%E5%B7%A5%E5%85%B7/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">goreplay 引流测试工具</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2020/07/31/03%E8%BD%AF%E4%BB%B6%E5%BC%80%E5%8F%91/02Rust/rust%E5%AE%8F/">
                        <span class="hidden-mobile">rust 宏</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  

  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
